﻿using System.Collections;
using System.Collections.Generic;
using Game;
using Game.UI;
using UnityEngine;
using ZYLFramework.Common;
using ZYLFramework.UI;

namespace ZYLFramework.Manage
{
    public delegate void EventDelegate(object[] objects);

    public class Event
    {
        public EventDelegate EventDelegate;

        public Event(EventDelegate eventDelegate)
        {
            EventDelegate = eventDelegate;
        }
    }

    public class EventManage:MonoSingleton<EventManage>
    {
        // 事件类型和事件注册对象列表
        private Dictionary<EventEnum,List<Event>> _eventDict;

        public EventManage()
        {
            _eventDict = new Dictionary<EventEnum, List<Event>>();
        }

        public int Register(EventEnum eventEnum,EventDelegate func)
        {
            if (func == null)
            {
                return -1;
            }
            
            if (!_eventDict.ContainsKey(eventEnum))
            {
               _eventDict.Add(eventEnum,new List<Event>()); 
            }

            var eventObject = new Event(func);
            var list = _eventDict[eventEnum];
            list.Add(eventObject);
            return list.Count - 1;
        }
        
        public void UnRegister(EventEnum eventEnum,int handle)
        {
            if (handle == -1)
            {
                return;
            }
            
            var list = _eventDict[eventEnum];
            if (list == null)
            {
                return;
            }
            list.RemoveAt(handle);
        }
        
        public void Notify(EventEnum eventEnum,params object[] obj)
        {
            var list = _eventDict.ContainsKey(eventEnum)?_eventDict[eventEnum]:null;
            if (list == null)
            {
                return;
            }
            for (int i = 0; i < list.Count; i++)
            {
                list[i]?.EventDelegate(obj);
            }
        }
        
        public void ClearEvents(EventEnum eventEnum){
            if (!_eventDict.ContainsKey(eventEnum))
            {
               return; 
            }
            _eventDict[eventEnum].Clear();
            _eventDict.Remove(eventEnum);
        }
        
        //封装一层给非Mono脚本调用
        public Coroutine OnStartCoroutine(IEnumerator routine)
        {
            return StartCoroutine(routine);
        }
    }
}